package com.pig4cloud.pig.module.controller.product;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.MathUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.mer.MerSelfVip;
import com.pig4cloud.pig.module.api.entity.mer.MerTable;
import com.pig4cloud.pig.module.api.entity.product.*;
import com.pig4cloud.pig.module.api.entity.property.Property;
import com.pig4cloud.pig.module.api.entity.wx.WxUserCashRecord;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.mer.IMerSelfVipService;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.mer.IMerTableService;
import com.pig4cloud.pig.module.service.product.*;
import com.pig4cloud.pig.module.service.property.IPropertyService;
import com.pig4cloud.pig.module.service.wx.IWxUserCashRecordService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * 订单详情内容  订单里面的 商品列Controller
 *
 * @author ruoyi
 * @date 2021-09-25
 */
@Validated
@Api(value = "订单详情内容  订单里面的 商品列控制器", tags = {"订单详情内容  订单里面的 商品列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/order/info")
public class ProductOrderInfoController {

    private final IProductOrderService productOrderService;
    private final IProductOrderInfoService productOrderInfoService;
    private final IProductAttrValueService productAttrValueService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final IMerService merService;
	private final IProductService productService;
	private final IWxUserCashRecordService wxUserCashRecordService;
    private final IMerSelfVipService merSelfVipService;
	private final IProductTypeService productTypeService;
	private final IMerTableService merTableService;


    /**
     * 查询订单详情内容  订单里面的 商品列列表
     */
    @ApiOperation("查询订单详情内容  订单里面的 商品列列表")
    @PreAuthorize("@pms.hasPermission('module:orderinfo:list')")
    @GetMapping("/list")
    public TableDataInfo<ProductOrderInfo> list(@Validated ProductOrderInfo productOrderInfo) {
        QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
        if(productOrderInfo.getOrderId() != null){
            qw.eq("order_id",productOrderInfo.getOrderId());
        }

        TableDataInfo<ProductOrderInfo> td = PageUtils.buildDataInfo(productOrderInfoService.page(PageUtils.buildPage(),qw));
        List<ProductOrderInfo> list = td.getData();
        list.forEach(orderInfo -> {
			if(StrUtil.isEmpty(orderInfo.getSkuName())){
				ProductAttrValue productAttrValue = productAttrValueService.findById(orderInfo.getSkuId());
				if(productAttrValue!=null){
					orderInfo.setSkuName(productAttrValue.getSku());
				}
			}
            Product product = productService.findById(orderInfo.getProductId());
            if(product!=null){
				orderInfo.setProductName(product.getStoreName());
			}

			if(orderInfo.getMerId()!= null){
				WxUserCashRecord cashRecord = wxUserCashRecordService.getRecordByOrderId(orderInfo.getMerId(),orderInfo.getOrderId(),orderInfo.getId());
				if(cashRecord!= null){
					orderInfo.setCashRecord(cashRecord);
				}
			}
        });
        ProductOrder order = productOrderService.findById(productOrderInfo.getOrderId());
        if(order!=null){
			Mer mer = merService.getById(order.getMerId());
			if(mer != null){
				order.setShopName(mer.getShopName());
			}

			Estate estate = estateService.findById(order.getEstateId());
			if(estate!=null){
				order.setEstateName(estate.getEstateName());
			}

			if(StrUtil.isNotEmpty(order.getRealName())){
				order.setRealName(EmojiParser.parseToUnicode(order.getRealName()));
			}

			Property property = propertyService.findById(order.getPropertyId());
			if(property!=null){
				order.setPropertyName(property.getPropertyName());
			}
		}
        Map<String,Object> map = new HashMap<>();
        map.put("order",order);

		QueryWrapper<MerTable> qwTable = new QueryWrapper<>();
		qwTable.eq("mer_id", order.getMerId());
		qwTable.orderByAsc("table_no");

		List<MerTable> merTables = merTableService.list(qwTable);
		map.put("merTables",merTables);

		MerTable table = merTableService.findById(order.getMerTableId());
		if(table!= null){
			map.put("table",table);
		}

		if(order.getSelfVipId()!=null){
			MerSelfVip selfVip = merSelfVipService.findById(order.getSelfVipId());
			map.put("selfVip",selfVip);
		}
        td.setOtherData(map);
        return td;
    }

    /**
     * 获取订单详情内容  订单里面的 商品列详细信息
     */
    @ApiOperation("获取订单详情内容  订单里面的 商品列详细信息")
    @PreAuthorize("@pms.hasPermission('module:orderinfo:query')")
    @GetMapping("/{id}")
    public R<ProductOrderInfo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        ProductOrderInfo productOrderInfo = productOrderInfoService.getById(id);
        if(productOrderInfo!=null){

		}
        return R.ok(productOrderInfo);
    }

    /**
     * 新增订单详情内容  订单里面的 商品列
     */
    @ApiOperation("新增订单详情内容  订单里面的 商品列")
    @PreAuthorize("@pms.hasPermission('module:orderinfo:add')")
    @SysLog("订单详情内容  订单里面的 商品列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody ProductOrderInfo productOrderInfo) {

		PigUser sysUser = SecurityUtils.getUser();
		productOrderInfo.setIsDel(0);
		productOrderInfo.setOpSysUserId(sysUser.getId());
		productOrderInfo.setOpSysUserName(sysUser.getName());
		Product product = productService.getById(productOrderInfo.getProductId());
		ProductType type = productTypeService.getById(product.getCateId());
		productOrderInfo.setDishType(type.getDishType());
		productOrderInfo.setProductName(product.getStoreName());
		if(productOrderInfo.getCount()!= null && productOrderInfo.getSinglePrice()!= null){
			double totalMoney = productOrderInfo.getCount() * productOrderInfo.getSinglePrice().doubleValue();
			productOrderInfo.setTotalMoney(BigDecimal.valueOf(MathUtil.getDoubleUp(totalMoney)));
		}
		boolean bl = productOrderInfoService.save(productOrderInfo);
		if(bl){
			int ret = productOrderInfoService.resetOrderTotalMoney(productOrderInfo);
			if (ret > 0){
				QueryWrapper<ProductOrderInfo> qw = new QueryWrapper<>();
				qw.eq("product_id",productOrderInfo.getProductId());
				qw.eq("order_id",productOrderInfo.getOrderId());
				TableDataInfo<ProductOrderInfo> td = PageUtils.buildDataInfo(productOrderInfoService.page(PageUtils.buildPage(),qw));
				List<ProductOrderInfo> orderInfos = td.getData();
				for (ProductOrderInfo orderInfo:orderInfos){
					orderInfo.setSkuName("默认");
					Product product1 = productService.getById(orderInfo.getProductId());
					orderInfo.setProductName(product1.getStoreName());
				}
				if(orderInfos!= null){
					System.out.println(orderInfos);
					List<ProductOrderInfo> Info = new ArrayList<>();
					Info.add(orderInfos.get(0));
					productOrderService.printAddAll(Info);
				}
			}
			return R.okByRow(ret > 0 ? 1 : 0);
		}
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 修改订单详情内容  订单里面的 商品列
     */
    @ApiOperation("修改订单详情内容  订单里面的 商品列")
    @PreAuthorize("@pms.hasPermission('module:orderinfo:edit')")
    @SysLog("订单详情内容  订单里面的 商品列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody ProductOrderInfo productOrderInfo) {
		PigUser sysUser = SecurityUtils.getUser();
		productOrderInfo.setOpSysUserId(sysUser.getId());
		productOrderInfo.setOpSysUserName(sysUser.getName());
		if (productOrderInfo.getSinglePrice()!=null){
			productOrderInfo.setTotalMoney(BigDecimal.valueOf(productOrderInfo.getSinglePrice().doubleValue() * productOrderInfo.getCount()));
		}
		if (productOrderInfo.getCount()!=null){
			ProductOrderInfo productOrderInfos = productOrderInfoService.selectByUniqueColumn("id",productOrderInfo.getId());
			productOrderInfo.setTotalMoney(BigDecimal.valueOf(productOrderInfos.getSinglePrice().doubleValue() * productOrderInfo.getCount()));
			productOrderInfo.setOrderId(productOrderInfos.getOrderId());
		}
        boolean bl = productOrderInfoService.updateById(productOrderInfo);
        if(bl){
            int ret = productOrderInfoService.resetOrderTotalMoney(productOrderInfo);
            return R.okByRow(ret > 0 ? 1 : 0);
        }
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 删除订单详情内容  订单里面的 商品列
     */
    @ApiOperation("删除订单详情内容  订单里面的 商品列")
    @PreAuthorize("@pms.hasPermission('module:orderinfo:remove')")
    @SysLog("订单详情内容  订单里面的 商品列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {

		PigUser sysUser = SecurityUtils.getUser();

		for (Long id : ids){
			ProductOrderInfo orderInfo = productOrderInfoService.findById(id);
			if(orderInfo!= null){
				orderInfo.setIsDel(1);
				orderInfo.setDelSysUserId(sysUser.getId());
				orderInfo.setDelSysUserName(sysUser.getName());
				orderInfo.setDelTime(new Date());
				boolean bl = productOrderInfoService.updateById(orderInfo);
				if(bl){
					int ret = productOrderInfoService.resetOrderTotalMoney(orderInfo);
					if(ret > 0){
						return R.okByRow(bl ? 1 : 0);
					}
				}
			}
		}
        return R.okByRow(0);
    }


	/**
	 * 分类打印选中的明细
	 */
	@ApiOperation("分类打印选中的明细")
	@PreAuthorize("@pms.hasPermission('module:orderinfo:remove')")
	@SysLog("分类打印选中的明细")
	@PostMapping("/print/{ids}")
	public R<Void> print(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {

		List<ProductOrderInfo> orderInfos = new ArrayList<>();
		for (Long id : ids){
			ProductOrderInfo orderInfo = productOrderInfoService.findById(id);
			if(orderInfo!= null){
				if(orderInfo.getIsDel() == 0){
					orderInfos.add(orderInfo);
				}
			}
		}
		productOrderService.printAddAll(orderInfos);
		return R.okByRow(1);
	}
}
